package control;

import java.io.IOException;
import java.util.ArrayList;


import client.Client;
//import entities.User;
import events.LoginEvent;
import events.LoginEventListener;
import msg.LogOutMessage;
import msg.UserAuthenticationMessage;

public class Login {
	
	private Client client;
	
	//private User user; //reference to the currently logged in user 
	
	private String warnning; //holds the current warnning string to be displayed by GUI
	
	private boolean active = false; //set to true if a user is currently logged in to some privilige other then guest
	
    public enum FailedState { WrongPassword , WrongUsername , AlreadyLogged , Default}
	
	private FailedState faildState = FailedState.Default;

	private ArrayList<LoginEventListener> listeners; // listeners for a login events
	
	public Login(Client tc) {
		this.client = tc;
		//this.user= new User();
		listeners = new ArrayList<LoginEventListener>();
	}
	
	// register listeners for login events 
	public synchronized void addLoginListener(LoginEventListener listener){
		listeners.add(listener);
	}
	
/*	public synchronized void removeLoginListener(LoginEventListener listener){
		listeners.remove(listener);
	}
*/

	public void authenticate(String user , String pass) {
		UserAuthenticationMessage msg = new UserAuthenticationMessage(user,pass);
		try {
			this.client.sendToServer(msg);
			System.out.println("authenticating...");
		}catch (IOException e) {e.printStackTrace();}
	}
	
	public void login(UserAuthenticationMessage msg){
			setWarnning(msg.getMessageString());
			
			if (msg.isAuthenticated()){
				
				this.setActive(true);
			}
			else{
			//	this.user = new User();
				this.setActive(false);
			}	
			LoginEvent e = new LoginEvent(this);
			for(LoginEventListener l : listeners)
				l.handleLoginEvent(e);
	}
	
	public void askForlogout() {
		//LogOutMessage logoutmsg = new LogOutMessage(user);
	//	try {
		//	client.sendToServer(logoutmsg);
		//	System.out.println("logging out...");
		//} catch (IOException e) {e.printStackTrace();}
	//	finally{
		//	this.user = new User();
			this.setActive(false);
			this.setFaildState(FailedState.Default);
			this.setWarnning(null);
			LoginEvent event = new LoginEvent(this);
			for(LoginEventListener l : listeners)
				l.handleLoginEvent(event);
		}
		
	//}
	
	//public User getUser() {
	//	return user;
//	}
	
//	public void setUser(User user) {
	//	this.user = user;
	//}

	public String getWarnning() {
		return warnning;
	}

	public void setWarnning(String warnning) {
		this.warnning = warnning;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public FailedState getFaildState() {
		return faildState;
	}

	public void setFaildState(FailedState faildState) {
		this.faildState = faildState;
	}


}